package com.example.shutdown_v1.service;

import com.example.shutdown_v1.entity.DailyInspectionRecord;
import com.example.shutdown_v1.entity.Sensor;
import com.example.shutdown_v1.entity.Shop;
import com.example.shutdown_v1.entity.SwitchStateRecord;
import com.example.shutdown_v1.repository.DailyInspectionRecordRepository;
import com.example.shutdown_v1.repository.SensorRepository;
import com.example.shutdown_v1.repository.ShopRepository;
import com.example.shutdown_v1.repository.SwitchStateRecordRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 每日巡检服务
 * 自动检查店铺的"三关一闭"状态
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class DailyInspectionService {

    private final ShopRepository shopRepository;
    private final SensorRepository sensorRepository;
    private final SwitchStateRecordRepository stateRecordRepository;
    private final DailyInspectionRecordRepository inspectionRecordRepository;
    private final AlarmService alarmService;

    /**
     * 执行指定店铺的巡检
     * @param shopId 店铺ID
     * @return 巡检记录
     */
    @Transactional
    public DailyInspectionRecord performInspection(Long shopId) {
        Shop shop = shopRepository.findById(shopId).orElse(null);
        if (shop == null) {
            log.warn("店铺不存在: {}", shopId);
            return null;
        }

        log.info("[巡检] 开始巡检店铺: {} (ID={})", shop.getName(), shopId);

        // 获取该店铺的所有传感器
        List<Sensor> sensors = sensorRepository.findByShopIdAndStatus(shopId, 1);
        
        if (sensors.isEmpty()) {
            log.warn("[巡检] 店铺 {} 没有注册的传感器", shop.getName());
            return null;
        }

        // 统计各状态传感器数量
        int totalSensors = sensors.size();
        int closedCount = 0;
        int openCount = 0;
        int unknownCount = 0;
        int offlineCount = 0;
        List<String> unclosedSensors = new ArrayList<>();

        LocalDateTime now = LocalDateTime.now();
        LocalDateTime offlineThreshold = now.minusMinutes(10); // 10分钟无数据视为离线

        for (Sensor sensor : sensors) {
            // 获取最新状态
            var latestStateOpt = stateRecordRepository
                    .findFirstBySensorIdOrderByRecordTimeDesc(sensor.getSensorId());

            if (latestStateOpt.isEmpty() || 
                latestStateOpt.get().getRecordTime().isBefore(offlineThreshold)) {
                // 离线
                offlineCount++;
                unclosedSensors.add(sensor.getSensorId() + "(离线)");
            } else {
                String state = latestStateOpt.get().getCurrentState();
                switch (state) {
                    case "closed":
                        closedCount++;
                        break;
                    case "open":
                        openCount++;
                        unclosedSensors.add(sensor.getSensorId() + "(开启)");
                        break;
                    default:
                        unknownCount++;
                        unclosedSensors.add(sensor.getSensorId() + "(未知)");
                        break;
                }
            }
        }

        // 判断是否合规（所有传感器都关闭才算合规）
        boolean isCompliant = (closedCount == totalSensors);

        // 生成巡检结果摘要
        String summary = String.format(
                "店铺[%s] 共%d个传感器，关闭%d个，开启%d个，未知%d个，离线%d个。%s",
                shop.getName(), totalSensors, closedCount, openCount, unknownCount, offlineCount,
                isCompliant ? "合规" : "不合规"
        );

        // 保存巡检记录
        DailyInspectionRecord record = new DailyInspectionRecord();
        record.setShopId(shopId);
        record.setInspectionTime(now);
        record.setTotalSensors(totalSensors);
        record.setClosedSensors(closedCount);
        record.setOpenSensors(openCount);
        record.setUnknownSensors(unknownCount);
        record.setOfflineSensors(offlineCount);
        record.setIsCompliant(isCompliant);
        record.setUnclosedSensorList(String.join(", ", unclosedSensors));
        record.setResultSummary(summary);

        inspectionRecordRepository.save(record);

        log.info("[巡检] {}", summary);

        // 如果不合规，生成告警
        if (!isCompliant && !unclosedSensors.isEmpty()) {
            alarmService.createUnclosedSwitchAlarm(shopId, unclosedSensors);
        }

        return record;
    }

    /**
     * 执行所有店铺的巡检
     */
    @Transactional
    public List<DailyInspectionRecord> performAllInspections() {
        List<Shop> activeShops = shopRepository.findByStatus(1);
        log.info("[巡检] 开始全店巡检，共 {} 个店铺", activeShops.size());

        List<DailyInspectionRecord> records = new ArrayList<>();
        for (Shop shop : activeShops) {
            try {
                DailyInspectionRecord record = performInspection(shop.getId());
                if (record != null) {
                    records.add(record);
                }
            } catch (Exception e) {
                log.error("[巡检] 店铺 {} 巡检失败", shop.getName(), e);
            }
        }

        log.info("[巡检] 全店巡检完成，共巡检 {} 个店铺", records.size());
        return records;
    }

    /**
     * 获取店铺最新巡检结果
     */
    public DailyInspectionRecord getLatestInspection(Long shopId) {
        return inspectionRecordRepository
                .findFirstByShopIdOrderByInspectionTimeDesc(shopId)
                .orElse(null);
    }
}

